package cn.rumoss.io;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class RepalceStringInFile {

	public static void main(String[] args) throws Exception {
		File file = new File("/data/gitee/Java8Fundamental/src/replaceMe.txt");
		InputStream input = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 使用 "aaa" 替换 "AAA"
		replaceString(input, baos, "AAA".getBytes(), "aaa".getBytes());
		byte[] data = baos.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		baos.reset();
		// 使用 "bbb" 替换 "BBB"
		replaceString(bais, baos, "BBB".getBytes(), "bbb".getBytes());
		data = baos.toByteArray();
		bais = new ByteArrayInputStream(data);
		baos.reset();
		// 使用 "ccc" 替换 "CCC"
		replaceString(bais, baos, "CCC".getBytes(), "ccc".getBytes());
		// 把替换后的流输出到文件
		File outFile = new File("/data/gitee/Java8Fundamental/src/reaplaceMeCopy.txt");
		FileOutputStream fos = new FileOutputStream(outFile);
		fos.write(baos.toByteArray());
		fos.close();
	}

	private static final void replaceString(InputStream is, OutputStream os, byte[] src, byte[] dst)
			throws IOException {
		if (src.length != dst.length)
			throw new IllegalArgumentException();
		BufferedInputStream bis = new BufferedInputStream(is);
		int data;
		starter: while ((data = bis.read()) != -1) {
			if (data == src[0]) {// 开始匹配目标字符串
				bis.mark(10);// 标记开始读取的位置
				for (int j = 1; j < src.length; j++) {
					int n = bis.read();
					if ((n == -1) || (n != src[j])) {// 发现不相同的内容,还原重新匹配
						bis.reset();// 重置刚才读过的内容
						os.write(data);
						continue starter;
					}
				}
				// 匹配完成,找到了目标字符串,执行替换
				os.write(dst);
			} else {
				os.write(data);
			}
		}
	}

}
